<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div id="app">
      <button @click="str = 'Child1'">btn1</button>
      <button @click="str = 'Child2'">btn2</button>
      <button @click="str = 'Child3'">btn3</button>

      <!-- <child1 v-if="num === 1"></child1>
      <child2 v-if="num === 2"></child2>
      <child3 v-if="num === 3"></child3> -->

      <!-- component组件用于做动态组件, 需要一个is属性， 对应的是组件名称 -->
      <!-- 动态组件默认情况下，会销毁移出的组件，会创建移入的组件 -->

      <!-- keep-alive表示缓存组件, 让动态组件切换的时候不被销毁 -->
      <keep-alive>
        <component :is="str"></component>
      </keep-alive>
    </div>

    <script src="../Vue.js"></script>
    <script>
      const Child1 = {
        template: `
          <div>
            child1
          </div>
        `,
        mounted() {
          console.log("child1 mounted");
        },
        beforeDestroy() {
          console.log("child1 beforeDestroy");
        },
      };

      let timer;
      const Child2 = {
        data() {
          return {
            count: 1,
          };
        },
        template: `
          <div>
            child2 - {{ count }}
          </div>
        `,
        mounted() {
          console.log("child2 mounted");
          // timer = setInterval(() => {
          //   this.count++;
          // }, 1000);
        },
        beforeDestroy() {
          console.log("child2 beforeDestroy");
        },
        activated() {
          // 被keep-alive缓存的组件激活时调用
          // console.log("激活了");
          timer = setInterval(() => {
            this.count++;
          }, 1000);
        },
        deactivated() {
          // 被keep-alive缓存的组件失活时调用
          // console.log("失活了");
          clearInterval(timer);
        },
      };

      const Child3 = {
        template: `
          <div>
            child3
          </div>
        `,
        mounted() {
          console.log("child3 mounted");
        },
        beforeDestroy() {
          console.log("child3 beforeDestroy");
        },
      };

      new Vue({
        el: "#app",
        data: {
          // num: 1,
          str: "Child1",
        },
        components: {
          Child1,
          Child2,
          Child3,
        },
      });
    </script>
  </body>
</html>
